//
//  YRMainTabBar.swift
//  YRSinaSwiftVersion
//
//  Created by 夜神月 on 16/4/8.
//  Copyright © 2016年 yr. All rights reserved.
//

import UIKit

class YRMainTabBar: UITabBar {
    var compseClosure:(() -> ())?
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        let buttonCount = 5
        // 设置宽度
        let width = frame.size.width / CGFloat(buttonCount)
        // 创建 frame
        let newFrame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
        var index = 0
        for subView in subviews {
            if subView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                subView.frame =  CGRectOffset(newFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
            }
        }
        // 计算
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.size.height)
        
    }
    
    // MARK: - 懒加载
    // @objc: 让OC可以调用我们swift的方法，系统默认会为所有的swift方法加上@objc, 如果方法加了private， 就不会帮我们加 @objc
    
    @objc private func didClickComposeButton() {
        print("didClickComposeButton")
        compseClosure?()
    }
    
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: .Normal)
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.addTarget(self, action: "didClickComposeButton", forControlEvents: .TouchUpInside)
        
        // 添加按钮到控制器
        self.addSubview(button)
        
        return button
    }()

}
